<template>
  <div>
    <el-form :model="form" :rules="rules" ref="form" >
      <el-form-item label="包材" prop="packingMaterialCode">
         <el-select v-model="form.packingMaterialCode" @change="packingMaterialChange" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-button @click='goodAddFun' style='margin:10px' type="primary">新增商品</el-button>
    <el-table
      ref="xTable"
      border
      resizable
      keep-source
      stripe
      highlight-current-row
      align="center"
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      height="300"
      :data="tableData"
    >
      <el-table-column prop="goodsName" label="商品名称" :edit-render="{name: 'ElSelect'}" >
        <template slot-scope="scope">
          <el-autocomplete
            v-model="scope.row.goodsName"
            :trigger-on-focus='false'
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect(scope.row,$event)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="goodCode" label="商品编码" :edit-render="{name: 'ElSelect'}" >
        <template slot-scope="scope">
          <el-autocomplete
            v-model="scope.row.goodCode"
            :trigger-on-focus='false'
            :fetch-suggestions="querySearchAsyncs"
            placeholder="请输入内容"
            @select="handleSelect(scope.row,$event)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量"  >
        <template slot-scope="scope">
          <el-input v-model="scope.row.quantity" placeholder="数量"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="50">
         <template slot-scope="scope">
          <el-tooltip content="删除" placement="top">
            <vxe-button type="text" @click="funcDel(scope)">
              <i class="el-icon-delete"/>
            </vxe-button>
          </el-tooltip>
         </template>
      </el-table-column>
    </el-table>
    <el-button @click='onSub' style='margin-top:10px;margin-left:80%'>保存</el-button>
  </div>
</template>
<script>
import { chooseData,searchByGoodCodeAndName, } from '@/api/packingMaterial/packingMaterial'
import request from '@/utils/request'
export default {
  data(){
    return{
      rules:{
        packingMaterialCode:[{ required: true, message: '请选择包材', trigger: 'blur' }]
      },
      form:{},
      options:[],
      tableData:[],
      isType:true
    }
  },
  created(){
    this.query()
  },
  methods:{
    query(){
      chooseData().then(res=>{
        this.options = res.data
      })
    },
    quantityBlur(e,val){
      let str = Number(e.quantity)
      if(!e.quantity)return
      let reg  = /^[1-9]\d*$/
      if(!reg.test(str)){
        this.isType = false
        this.$message.error('请输入大于0的整数')
      }else{
        this.isType = true
      }
    },
    funcDel(val){
      this.$alert('确定删除', '删除', {
        confirmButtonText: '确定',
        callback: action => {
          let rowIndex = val.rowIndex;
          this.tableData.splice(rowIndex,1)
        }
      });
    },
    packingMaterialChange(val){
      let obj = this.options.find(v=>v.code === val)
      this.form.packingMaterialName = obj?obj.name:''
    },
    //编码
    querySearchAsyncs(queryString, cb){
      if(!queryString)return
      let data = {goodCode:queryString}
      searchByGoodCodeAndName(data).then(res=>{
        let restaurants = res.data.map(v=>{
          return {...v,value:v.goodCode}
        })
        cb(restaurants)
      })
    },
    //名称
    querySearchAsync(queryString, cb){
      if(!queryString)return
      let data = {goodsName:queryString}
      searchByGoodCodeAndName(data).then(res=>{
        let restaurantss = res.data.map(v=>{
          return {...v,value:v.name}
        })
        cb(restaurantss)
      })

    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(row,item){
      row.goodsName = item.name
      row.goodCode = item.goodCode
      row.goodsCode = item.code
    },
    goodAddFun(){
      this.tableData.push({})
    },
    onSub(){
      const {tableData} = this
      let len = tableData.length
      if(len === 0)return this.$message.error('请新增商品')
      let reg  = /^[1-9]\d*$/
      for(let i = 0; i < len; i++){
        if (!tableData[i].goodsName || tableData[i].goodsName === '') {
          this.$message.error(`请先选择第${i+1}行商品`)
          return
        }
        if (!reg.test(tableData[i].quantity)) {
          this.$message.error(`第${i+1}行的数量必须是大于0的整数`)
          return
        }
      }
      this.$refs['form'].validate((valid) => {
        if(valid){
          let data = this.form
          data.packingMaterialGoodsList = tableData
          return request({
            url: '/wms/packingMaterialGoods',
            method: 'post',
            data
          }).then(res=>{
            this.$emit('concen');
            this.$message.success(res.msg)
          })
        }
      })

    },
  }
}
</script>
